import React, { FC, JSX } from 'react'
import {
    DndContext,
    closestCenter,
    MouseSensor,
    useSensor,
    DragEndEvent,
    useSensors,
} from '@dnd-kit/core'
import {
    //   arrayMove,
    SortableContext,
    verticalListSortingStrategy,
} from '@dnd-kit/sortable'

type PropsType = {
    children: JSX.Element | JSX.Element[]
    items: Array<{ id: string; [key: string]: any }>
    onDragEnd: (oldIndex: number, newIndex: number) => void
}

const SortableContainer: FC<PropsType> = (props: PropsType) => {
    const sensors = useSensors(
        useSensor(MouseSensor, {
            // 拖拽活动限制
            activationConstraint: {
                distance: 10, // 拖拽对象移动距离小于10px不会触发拖拽，超过10px才会触发
            },
        })
    )
    const { children, items, onDragEnd } = props

    // 拖拽结束事件
    function handleDragEnd(event: DragEndEvent) {
        const { active, over } = event
        if (over === null) return

        if (active.id !== over.id) {
            const oldIndex = items.findIndex(c => c.fe_id === active.id)
            const newIndex = items.findIndex(c => c.fe_id === over.id)
            onDragEnd(oldIndex, newIndex)
        }
    }
    return (
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
            <SortableContext items={items} strategy={verticalListSortingStrategy}>
                {children}
            </SortableContext>
        </DndContext>
    )
}
export default SortableContainer
